class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
public class LowestCommonAncestor {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }

        TreeNode rootLeft = lowestCommonAncestor(root.left,p,q);
        TreeNode rootRight = lowestCommonAncestor(root.right,p,q);

        if (rootLeft != null && rootRight != null) {
            return root;
        }else if(rootLeft != null){
            return rootLeft;
        }else {
            return rootRight;
        }
    }
}
